import React, { useState, useEffect } from 'react';
import { message, Spin, Select } from 'antd';
import moment from 'moment';
import { export_json_to_excel } from '@/utils/fileExport.js';
import {
  CaretDownOutlined,
  UploadOutlined,
  DownSquareOutlined,
  UpSquareOutlined,
  // @ts-ignore
} from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';
import DeclarePlan from './components/DeclarePlan';
import DeclareDetailList from './components/DeclareDetailList';
import DeclareDetailCharts from './components/DeclareDetailCharts';
import type {
  IFormValue,
  IPostQueryShortForecastCurveAdjustmentParamsType,
  IShortForecastCurveAdjustmentDataType,
  IDealElementOptions,
  IQueryIssuePlanListDataType,
} from '../type';
import { IStepsType } from '../type';
import {
  ITitleType,
  ISideType,
  IUnitType,
  IExecuteStatusType,
  IShorttermForecastingRedesignPermissions,
} from '../type';
import { postQueryIssuePlanList, postQueryShortForecastCurveAdjustment } from '../service';
import {
  titleMap,
  declareDetailDataChannelOptions,
  defaultPointerNum,
  declareDetailDataChannelUnitOptions,
  sideOptions,
} from '../dictionary';
import { havePermissions, TIME_ENUM, ToFixed } from '../tool';
import { ExplainTitle } from '../components/index';

import styles from './index.less';

interface IProps {
  /**
   * 请求数据
   */
  formValue: IFormValue;
  /**
   * 是否需要重新刷新数据
   */
  activeKey?: number;
  /**
   * 权限
   */
  buttonPermissions?: any;
  /**
   * 交易单元数据
   */
  dealElementOptions?: IDealElementOptions[];
  /**
   * activeStep
   */
  activeStep?: IStepsType;
  /**
   * 申报计划列表数据
   */
  queryIssuePlanListData?: any;
}

const DeclareToPerform = (props: IProps) => {
  const { formValue, activeKey, buttonPermissions, activeStep, queryIssuePlanListData } = props;
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isError, setIsError] = useState<boolean>(false);
  const [data, setData] = useState<IQueryIssuePlanListDataType[]>(); // 申报计划数据
  const [declareDetailData, setDeclareDetailData] = useState<
    IShortForecastCurveAdjustmentDataType[]
  >([]); // 申报详情数据
  const [record, setRecord] = useState<IQueryIssuePlanListDataType>(); // 申报时间；
  const [disabled, setDisabled] = useState<boolean>(false); // 是否可以导出
  const [isSpread, setIsSpread] = useState<boolean>(false); // 是否展开
  const [unit, setUnit] = useState<IUnitType>(IUnitType.POWER_UNIT);
  const [side, setSide] = useState<ISideType>(ISideType.GENERATE);

  const dataKey = 'D-1';

  const _subTitle =
    record?.issueTime && record?.executeStatus === IExecuteStatusType.EXECUTED
      ? `${moment(record?.issueTime).format('YYYYMMDD HHmm')}申报`
      : '';

  // 获取申报详情
  const getDeclareDetailDetail = async (
    params: IPostQueryShortForecastCurveAdjustmentParamsType,
  ) => {
    setIsLoading(true);
    setDisabled(true);
    const res = await postQueryShortForecastCurveAdjustment(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setIsError(false);
      setDisabled(false);
      setDeclareDetailData(res?.data[dataKey]?.dataList || []);
    } else {
      setIsError(true);
      message.error(res?.message || '系统异常');
    }
    setIsLoading(false);
  };

  // 初始化数据
  const fetchData = async (params: IFormValue) => {
    setLoading(true);
    // const res = await postQueryIssuePlanList(params);
    const res = queryIssuePlanListData;
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setError(false);
      setData(res?.data || []);
      setRecord(res?.data[0] || {});
      setUnit(IUnitType.POWER_UNIT);
      const _params: IPostQueryShortForecastCurveAdjustmentParamsType = {
        adjustmentId: res?.data[0]?.adjustmentId ?? undefined,
        startDate: params?.calendarDate,
        endDate: params?.calendarDate,
        forecastId: res?.data[0]?.forecastId ?? undefined,
        issueRateId: res?.data[0]?.issueRateId ?? undefined,
        executeStatus: res?.data[0]?.executeStatus,
        stationId: params?.stationId,
        unit: unit || IUnitType.POWER_UNIT,
        side: side || ISideType.GENERATE,
        provinceId: formValue?.provinceId,
      };
      getDeclareDetailDetail(_params);
    } else {
      setError(true);
      message.error(res?.message || '系统异常');
    }
    setLoading(false);
  };

  // 改变数据口径
  const onChangeUnit = (e: IUnitType) => {
    if (e !== unit) {
      const _params: IPostQueryShortForecastCurveAdjustmentParamsType = {
        adjustmentId: record?.adjustmentId ?? undefined,
        startDate: formValue?.calendarDate,
        endDate: formValue?.calendarDate,
        forecastId: record?.forecastId ?? undefined,
        issueRateId: record?.issueRateId ?? undefined,
        executeStatus: record?.executeStatus,
        stationId: formValue?.stationId,
        unit: e || IUnitType.POWER_UNIT,
        side: side || ISideType.GENERATE,
        provinceId: formValue?.provinceId,
      };
      getDeclareDetailDetail(_params);
      setUnit(e);
    }
  };

  // 改变数据来源
  const onChangeSide = (e: ISideType) => {
    if (e !== side) {
      const _params: IPostQueryShortForecastCurveAdjustmentParamsType = {
        adjustmentId: record?.adjustmentId ?? undefined,
        startDate: formValue?.calendarDate,
        endDate: formValue?.calendarDate,
        forecastId: record?.forecastId ?? undefined,
        issueRateId: record?.issueRateId ?? undefined,
        executeStatus: record?.executeStatus,
        stationId: formValue?.stationId,
        unit: unit,
        side: e,
        provinceId: formValue?.provinceId,
      };
      getDeclareDetailDetail(_params);
      setSide(e);
    }
  };

  // 查看申报计划详情
  const onShow = (_data: IQueryIssuePlanListDataType) => {
    setRecord(_data);
    setUnit(IUnitType.POWER_UNIT);
    setIsSpread(false);
    const _params: IPostQueryShortForecastCurveAdjustmentParamsType = {
      adjustmentId: _data?.adjustmentId ?? undefined,
      startDate: formValue?.calendarDate,
      endDate: formValue?.calendarDate,
      forecastId: _data?.forecastId ?? undefined,
      issueRateId: _data?.issueRateId ?? undefined,
      executeStatus: _data?.executeStatus,
      stationId: formValue?.stationId,
      unit: IUnitType.POWER_UNIT,
      side: ISideType.GENERATE,
      provinceId: formValue?.provinceId,
    };
    getDeclareDetailDetail(_params);
  };

  // 导出
  const handleExportFiles = () => {
    if (disabled) {
      return;
    }
    const resoult = havePermissions(
      IShorttermForecastingRedesignPermissions.EXPORTBUTTON,
      buttonPermissions,
    );
    const { calendarDate, provinceName, stationName } = formValue;
    const _issueTime = calendarDate ? moment(calendarDate).format('YYYY.MM.DD') : '';
    if (resoult) {
      const dataFalt: any[] = [];
      const _pointerNums = TIME_ENUM(defaultPointerNum);
      const header = ['类型'];
      _pointerNums?.forEach((item) => {
        header.push(item);
      });
      declareDetailData.forEach((x) => {
        const { pointList, dataSourceName = '-' } = x || {};
        const _values: (string | number)[] = [dataSourceName];
        if (pointList[_issueTime]) {
          pointList[_issueTime].forEach((item) =>
            _values.push(item?.value || item?.value === 0 ? ToFixed(item?.value) : '-'),
          );
        }
        // if (Object.values(pointList) && Object.values(pointList)[0]) {
        //   Object.values(pointList)[0].forEach((item: any) => _values.push(item?.value ?? '-'));
        // }
        dataFalt.push(_values);
      });
      const _time = moment(calendarDate).format('YYYY-MM-DD');
      const _provinceName = provinceName || '';
      const _unitName =
        declareDetailDataChannelUnitOptions.find((item) => item.value === unit)?.label || '';
      const _sideName = sideOptions.find((item) => item.value === side)?.label || '';
      const params = {
        header,
        data: dataFalt,
        filename: `${_time}_${_provinceName}_${stationName} 申报详情${record?.issueTime}申报(${_sideName}-${_unitName})`,
      };
      export_json_to_excel(params);
    }
  };

  // 展开/收起
  const onSpread = () => {
    setIsSpread(!isSpread);
  };

  useEffect(() => {
    if (
      formValue?.calendarDate &&
      formValue.provinceId &&
      formValue.stationId &&
      activeStep === IStepsType.DECLARE_TO_PERFORM
    ) {
      fetchData(formValue);
    }
  }, [activeKey]);

  return (
    <div className={styles.container}>
      {loading ? (
        <Spin />
      ) : error ? (
        <TRDefault type={'error'} message={'系统异常'} />
      ) : data?.length ? (
        <div className={styles.main}>
          <div className={styles.declarePlan}>
            <DeclarePlan data={data} id={record?.id} onShow={onShow} />
          </div>
          <div className={styles.bottom}>
            <div
              className={
                isSpread || isLoading || isError
                  ? styles.isSpreadDeclareDetail
                  : styles.declareDetail
              }
            >
              <div className={styles.header}>
                <div className={styles.left}>
                  <ExplainTitle
                    title={titleMap[ITitleType.DECLARE_DETAIL].title}
                    subTitle={_subTitle}
                  />
                </div>
                <div className={styles.right}>
                  <div className={styles.select}>
                    <Select
                      value={side}
                      options={sideOptions as any}
                      suffixIcon={<CaretDownOutlined />}
                      bordered={false}
                      onChange={onChangeSide}
                    />
                  </div>
                  <div className={styles.select}>
                    <Select
                      value={unit}
                      options={declareDetailDataChannelOptions as any}
                      suffixIcon={<CaretDownOutlined />}
                      bordered={false}
                      onChange={onChangeUnit}
                    />
                  </div>
                  <div
                    className={`${disabled && styles.disabledButton} ${styles.button}`}
                    onClick={handleExportFiles}
                  >
                    <UploadOutlined
                      className={`${disabled && styles.disabledButtonLogo} ${styles.buttonLogo}`}
                    />
                    导出
                  </div>
                  <div className={styles.spread} onClick={onSpread}>
                    {isSpread ? (
                      <UpSquareOutlined className={styles.spreadLogo} />
                    ) : (
                      <DownSquareOutlined className={styles.spreadLogo} />
                    )}
                    {isSpread ? '收起' : '展开'}
                  </div>
                </div>
              </div>
              <div className={isLoading || isError ? styles.emptysmBottom : styles.bottom}>
                {isLoading ? (
                  <Spin />
                ) : isError ? (
                  <TRDefault type={'error'} message={'系统异常'} />
                ) : declareDetailData?.length ? (
                  <div className={styles.declareDetailContent}>
                    <div className={styles.declareDetailCharts}>
                      <DeclareDetailCharts
                        data={declareDetailData}
                        issueTime={formValue?.calendarDate}
                        unit={unit}
                      />
                    </div>
                    {isSpread ? (
                      <div className={styles.declareDetailList}>
                        <DeclareDetailList
                          data={declareDetailData}
                          issueTime={formValue?.calendarDate}
                        />
                      </div>
                    ) : null}
                  </div>
                ) : (
                  <TRDefault type={'emptysm'} message={'暂无数据'} />
                )}
              </div>
            </div>
          </div>
        </div>
      ) : (
        <TRDefault type={'emptysm'} message={'暂无数据'} />
      )}
    </div>
  );
};

export default DeclareToPerform;
